package com.chenailin.www.controller;

import com.chenailin.www.pojo.*;
import com.chenailin.www.service.AppointmentService;
import com.chenailin.www.service.DepartmentService;
import com.chenailin.www.service.DoctorService;
import com.chenailin.www.util.DateUtil;

import java.time.LocalDate;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

import static com.chenailin.www.common.Schedule.getTimeBySlot;
import static com.chenailin.www.util.MenuUtil.getConfirmation;

public class AppointmentController {
    private final AppointmentService appointmentService = new AppointmentService();
    private final DepartmentService departmentService = new DepartmentService();
    private final DoctorService doctorService = new DoctorService();
    private final Scanner sc = new Scanner(System.in);

    // 挂号功能
    public void appointmentRegister(Student student) {
        try {
            // 步骤1: 是否通过验证
            if (!appointmentService.isVerified(student.getStuId())) {
                System.out.println("还未通过验证，请先验证身份！");
                return;
            }

            // 步骤2: 选择科室
            Department department = selectDepartment();

            // 步骤3: 选择日期
            LocalDate date = selectDate();

            // 步骤4: 选择医生
            Doctor doctor = selectDoctor(department);

            // 步骤5: 选择时间段
            int slot = selectSchedule(doctor);
            if (slot == 0) {
                return;
            }

            Appointment appointment = new Appointment(date, department.getDepartId(), doctor.getDocId(), slot, student.getStuId());

            if(appointmentService.createAppointment(appointment) && appointmentService.selectDoctor(doctor.getDocId(), slot)) {
                System.out.println("\n挂号成功！");
            } else {
                System.out.println("挂号失败，请检查输入数据");
            }
        } catch (Exception e) {
            System.err.println("预约失败: " + e.getMessage());
        }
    }

    // 选择科室
    private Department selectDepartment() {
        System.out.println("\n=== 选择科室 ===");
        List<Department> departments = departmentService.getAllDepartments();
        departments.forEach(d -> System.out.println(d.getDepartId() + ". " + d.getDepartName()));
        System.out.print("请选择科室编号: ");
        int departId = sc.nextInt();
        sc.nextLine();
        Department selected = departments.stream()
                .filter(d -> d.getDepartId() == departId)
                .findFirst()
                .orElse(null);
        if (selected == null) {
            System.out.println("无效的医生编号，请重新选择！");
            return selectDepartment(); // 递归重试
        }
        return selected;
    }

    // 选择日期
    private LocalDate selectDate() {
        System.out.println("\n=== 选择日期 ===");
        appointmentService.showAvailableDates();
        return handleDateSelection();
    }

    // 选择医生
    private Doctor selectDoctor(Department department) {
        System.out.println("\n=== 选择医生 ===");
        List<Doctor> doctors = doctorService.findDoctorByDepartment(department.getDepartId());
        doctors.forEach(d -> System.out.printf("%d. %s\n", d.getDocId(), d.getDocName()));
        System.out.print("请选择医生编号: ");
        int doctorId = sc.nextInt();
        sc.nextLine();
        Doctor selected = doctors.stream()
                .filter(d -> d.getDocId() == doctorId)
                .findFirst()
                .orElse(null);
        if (selected == null) {
            System.out.println("无效的科室编号，请重新选择！");
            return selectDoctor(department); // 递归重试
        }
        return selected;
    }

    // 选择时间段
    private int selectSchedule(Doctor doctor) {
        System.out.println("\n=== 选择时间段 ===");
        System.out.println("\n此医生的排班：");
        if (doctorService.getUnSelectedSchedule(doctor.getDocId()) != null && !doctorService.getUnSelectedSchedule(doctor.getDocId()).isEmpty()) {
            doctorService.getUnSelectedSchedule(doctor.getDocId()).forEach(slot ->
                    System.out.printf("- %d. %s\n", slot,getTimeBySlot(slot)));
        } else {
            System.out.println("(暂无排班信息)");
            return 0;
        }
        System.out.print("请输入想预约的时间段编号：");
        int slot = sc.nextInt();
        if (!doctorService.getUnSelectedSchedule(doctor.getDocId()).contains(slot)) {
            System.out.println("该时间段不可选择！");
            return selectSchedule(doctor);
        }
        return slot;

    }

    // 查看挂号记录
    public void listAppointments(Student student) {
        System.out.println("\n=== 我的预约记录 ===");
        List<Appointment> appointments = appointmentService.getUserAppointments(student.getStuId());
        if (appointments.isEmpty()) {
            System.out.println("暂无预约记录");
            return;
        }
//        System.out.println(getTimeBySlot(1));
        appointments.forEach(appointment ->
                System.out.printf("预约号:%-5d 医生:%-10s 日期:%s 具体时间段: %d. %s\n",
                        appointment.getId(),
                        doctorService.getDoctorDetail(appointment.getDoctorId()).getDocName(),
                        DateUtil.formatDateWithWeekday(appointment.getAppointmentTime()),
                        appointment.getSchedule(),
                        getTimeBySlot(appointment.getSchedule())
                )
        );
    }

    // 取消预约
    public void cancelAppointment(Student student) {
        System.out.println("\n=== 取消预约 ===");
        if (appointmentService.getUserAppointments(student.getStuId()) == null) {
            System.out.println("暂无挂号记录");
            return;
        }
        listAppointments(student);
        System.out.print("请输入要取消的预约id: ");
        int id = sc.nextInt();
        sc.nextLine();
        try {
            if (!getConfirmation("确定要取消预约吗？")) {
                return;
            }
            if(appointmentService.cancelAppointment(id) && appointmentService.unSelectDoctor(id)) {
                System.out.println("取消成功");
            } else {
                System.out.println("取消失败，请检查输入数据");
            }
        } catch (Exception e) {
            System.err.println("取消失败: " + e.getMessage());
        }
    }

    // 处理用户选择
    public LocalDate handleDateSelection() {
        while (true) {
            System.out.print("请输入日期序号（1-7）：");
            try {
                int choice = sc.nextInt();
                sc.nextLine();
                LocalDate selectedDate = DateUtil.getDateByChoice(choice);
                System.out.println("已选择：" + DateUtil.formatDateWithWeekday(selectedDate));
                return selectedDate;
            } catch (InputMismatchException e) {
                System.out.println("请输入有效数字！");
                sc.nextLine();
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }
    }

}